package com.dingding.manager.modules.system.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.manager.common.beans.sys.CityRefOrganization;
import com.dingding.manager.common.beans.sys.Organization;
import com.dingding.manager.common.dao.Db;
import com.dingding.manager.common.dao.Page;
import com.dingding.manager.core.shiro.ShiroKit;
import com.dingding.manager.core.shiro.ShiroUser;
import com.dingding.manager.core.util.ToolUtil;
import com.dingding.manager.modules.system.dao.OrganizationDao;
import com.dingding.manager.modules.system.dto.organization.ReqOrganizationListDTO;
import com.dingding.manager.modules.system.dto.organization.ResOrganizationDTO;
import com.dingding.manager.modules.system.sql.OrganizationSQL;

/**
 * 
 * @ClassName: OrganizationDaoImpl
 * @Description: 机构管理dao实现类
 * @author SUNZHICHENG
 * @date 2016年12月4日 上午11:56:14
 * @version V2.6.2
 */
@Component("organizationDao")
public class OrganizationDaoImpl implements OrganizationDao {

	private static Logger logger = Logger.getLogger(OrganizationDaoImpl.class);

	/**
	 * @Description: 根据id查询机构信息
	 * @date 2016年12月4日 下午6:59:41
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public ResOrganizationDTO getOrganizationById(Integer id) {
		return Db.querySqlFirst(ResOrganizationDTO.class, OrganizationSQL.ORGANIZATION_INFO, id);

	}

	/**
	 * @Description: 获取所有机构
	 * @date 2016年12月5日 下午3:19:22
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public List<Organization> getOrganizationList() {

		return Db.querySqlList(Organization.class, OrganizationSQL.QUERY_ORGANIZATION_LIST);

	}

	/**
	 * @Description:删除机构信息
	 * @date 2016年12月5日 下午7:12:20
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public boolean deleteOrganization(Integer id) {

		// 获取当前登录用户信息
		ShiroUser shiroUser = ShiroKit.getUser();
		Integer currentId = shiroUser.getId();

		Organization organization = Db.findById(id, Organization.class);
		if (organization != null) {
			// 0 未删除 1 删除
			organization.setDelFlag(1);
			organization.setUpdateUserId(currentId);
			organization.setUpdateTime(new Date());
			Db.saveOrUpdate(organization);
			return true;
		}
		return false;
	}

	/**
	 * @Description: 启用、禁用
	 * @date 2016年12月5日 下午7:13:52
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public boolean modifyOrganizationState(Integer id, Integer state) {
		// 获取当前登录用户信息
		ShiroUser shiroUser = ShiroKit.getUser();
		Integer currentId = shiroUser.getId();

		Organization organization = Db.findById(id, Organization.class);
		if (organization != null) {
			// 0 未删除 1 删除
			organization.setOrganizationStatus(state);
			organization.setUpdateUserId(currentId);
			organization.setUpdateTime(new Date());
			Db.saveOrUpdate(organization);
			return true;
		}
		return false;
	}

	/**
	 * @Description: 根据公司类型获取公司列表
	 * @param organizationType
	 * @date 2016年12月6日 上午11:32:47
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public List<Organization> getOrganizationListByType(Integer organizationType) {

		if (ToolUtil.isNotEmpty(organizationType)) {
			StringBuffer sql = new StringBuffer(
					" SELECT * FROM dd_organization m where m.delFlag = 0 AND m.organizationStatus = 1  ");

			/**
			 * 获取所有公司 当类型为-1
			 */
			if(organizationType != -1){
				// 根据具体的公司类型获取相应的数据，0 则获取类型为总公司的数据
				sql.append(" AND m.organizationType = ?  ");
			}
			
			sql.append("  ORDER BY m.createTime DESC  ");
			
			return Db.querySqlList(Organization.class, sql.toString(), organizationType);
		}
		return null;
	}

	/**
	 * @Description:获取公司列表（或组合查询）
	 * @date 2016年12月6日 下午8:02:57
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public Page<ResOrganizationDTO> getOrganizationList(ReqOrganizationListDTO reqOrganizationListDTO, Integer start,
			Integer length) {

		List<Object> params = new ArrayList<Object>();

		StringBuffer sql = new StringBuffer(
				"  select a.organizationId organizationId, a.parentId parentId, e.provice_id proviceId, e.provice_name proviceName,c.sysCityId sysCityId,c.cityName cityName, "
						+ " a.organizationName organizationName, a.organizationAddr organizationAddr,a.businessLicence businessLicence,a.contacts contacts,a.contactsNumber contactsNumber, "
						+ " a.contactsEmail contactsEmail, DATE_FORMAT(a.licenseStartDate,'%Y-%m-%d %H:%I:%S') licenseStartDate, DATE_FORMAT(a.licenseEndDate,'%Y-%m-%d %H:%I:%S') licenseEndDate, "
						+ " a.organizationType organizationType,a.organizationStatus organizationStatus,a.remarks remarks,DATE_FORMAT(a.createTime,'%Y-%m-%d %H:%I:%S') createTime, "
						+ " DATE_FORMAT(a.updateTime,'%Y-%m-%d %H:%I:%S') updateTime,a.createUserId createUserId, a.updateUserId updateUserId from dd_organization a, "
						+ " dd_city_ref_organization b, dd_sys_city c ,dd_sys_provice_city d ,dd_sys_province e  where a.organizationId = b.organizationId and b.cityId = c.sysCityId "
						+ " and c.sysCityId = d.sysCityId and d.proviceId = e.provice_id and a.delFlag = 0 ");

		Integer row = (int) Math.ceil((double) (start + 1) / length);
		Page<ResOrganizationDTO> page = new Page<>(row, length);

		// 获取用户有权限访问的机构集合
		/*List<Integer> organizationList = ShiroKit.getOrganizationIdList();
		if (organizationList.size() > 0) {
			params.addAll(organizationList);
			sql.append(" and a.organizationId IN ("+SqlUtil.parse(organizationList)+" ) ");
		}*/

		if (reqOrganizationListDTO != null) {

			// 省份
			if (ToolUtil.isNotEmpty(reqOrganizationListDTO.getProviceId())) {
				sql.append(" AND e.provice_id = ? ");
				params.add(reqOrganizationListDTO.getProviceId());
			}
			// 城市
			if (ToolUtil.isNotEmpty(reqOrganizationListDTO.getCityId())) {
				sql.append(" AND c.sysCityId = ? ");
				params.add(reqOrganizationListDTO.getCityId());
			}
			// 状态
			if (ToolUtil.isNotEmpty(reqOrganizationListDTO.getState())) {
				sql.append(" AND a.organizationStatus = ? ");
				params.add(reqOrganizationListDTO.getState());
			}
			// 名称、注册号、公司联系人、联系电话
			if (ToolUtil.isNotEmpty(reqOrganizationListDTO.getCondition())) {
				sql.append(
						" AND ( a.organizationName LIKE ? or a.businessLicence LIKE ? or a.contacts LIKE ? or a.contactsNumber LIKE ? ) ");
				params.add("%" + reqOrganizationListDTO.getCondition() + "%");
				params.add("%" + reqOrganizationListDTO.getCondition() + "%");
				params.add("%" + reqOrganizationListDTO.getCondition() + "%");
				params.add("%" + reqOrganizationListDTO.getCondition() + "%");
			}

		}
		sql.append(" ORDER BY a.createTime ");

		return Db.querySqlByPage(ResOrganizationDTO.class, page, sql.toString(), params.toArray());
	}

	/**
	 * @Description: 根据省份、城市获取机构
	 * @date 2016年12月7日 下午8:17:477
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public List<ResOrganizationDTO> getOrganization(Integer proviceId, Integer sysCityId) {
		List<Object> params = new ArrayList<Object>();

		StringBuffer sql = new StringBuffer(
				"  select a.organizationId organizationId, e.provice_id proviceId, e.provice_name proviceName,c.sysCityId sysCityId,c.cityName cityName, "
						+ " a.organizationName organizationName, a.organizationAddr organizationAddr,a.businessLicence businessLicence,a.contacts contacts,a.contactsNumber contactsNumber, "
						+ " a.contactsEmail contactsEmail, DATE_FORMAT(a.licenseStartDate,'%Y-%m-%d %H:%I:%S') licenseStartDate, DATE_FORMAT(a.licenseEndDate,'%Y-%m-%d %H:%I:%S') licenseEndDate, "
						+ " a.organizationType organizationType,a.organizationStatus organizationStatus,a.remarks remarks,DATE_FORMAT(a.createTime,'%Y-%m-%d %H:%I:%S') createTime, "
						+ " DATE_FORMAT(a.updateTime,'%Y-%m-%d %H:%I:%S') updateTime,a.createUserId createUserId, a.updateUserId updateUserId from dd_organization a, "
						+ " dd_city_ref_organization b, dd_sys_city c ,dd_sys_provice_city d ,dd_sys_province e  where a.organizationId = b.organizationId and b.cityId = c.sysCityId "
						+ " and c.sysCityId = d.sysCityId and d.proviceId = e.provice_id and a.delFlag = 0 AND a.organizationStatus = 1 ");

		if (ToolUtil.isNotEmpty(proviceId)) {
			sql.append(" AND e.provice_id = ?  ");
			params.add(proviceId);
		}
		if (ToolUtil.isNotEmpty(sysCityId)) {
			sql.append(" AND c.sysCityId =  ? ");
			params.add(sysCityId);
		}
		return Db.querySqlList(ResOrganizationDTO.class, sql.toString(), params.toArray());
	}

	/**
	 * @Description: 添加机构
	 * @date 2016年12月8日 下午9:32:51
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public boolean addOrganization(Organization organization) {
		Db.saveOrUpdate(organization);
		return true;
	}

	/**
	 * 
	 * @Title: getOrganizationByDriverId @Description: 根据用户id查询用户的机构 @param
	 * driverId @param @return 参数说明 @return Organization 返回类型 @throws
	 */
	@Override
	public Organization getOrganizationByUserId(Integer userId) {
		return Db.querySqlFirst(Organization.class, OrganizationSQL.QUERY_ORGANIZATION_BY_USERID, userId);
	}

	/**
	 * @Description: 添加城市机构管理关系
	 * @date 2016年12月8日 下午9:40:14
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public boolean addCityRefOrganization(CityRefOrganization cityRefOrganization) {
		Db.saveOrUpdate(cityRefOrganization);
		return false;
	}

	/**
	 * @Description: 根据省份、城市获取机构
	 * @date 2016年12月7日 下午8:17:47
	 * @author hufan
	 * @since V2.6.2
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Integer> getOrganizationIds(Integer proviceId, Integer sysCityId) {
		List<Object> params = new ArrayList<Object>();

		StringBuffer sql = new StringBuffer("  select a.organizationId organizationId from dd_organization a, "
				+ " dd_city_ref_organization b, dd_sys_city c ,dd_sys_provice_city d ,dd_sys_province e  where a.organizationId = b.organizationId and b.cityId = c.sysCityId "
				+ " and c.sysCityId = d.sysCityId and d.proviceId = e.provice_id and a.delFlag = 0 ");

		if (ToolUtil.isNotEmpty(proviceId)) {
			sql.append(" AND e.provice_id = ?  ");
			params.add(proviceId);
		}
		if (ToolUtil.isNotEmpty(sysCityId)) {
			sql.append(" AND c.sysCityId =  ? ");
			params.add(sysCityId);
		}
		return Db.querySqlBasicTranslationList(Integer.class, sql.toString(), params.toArray());
	}

	/**
	 * @Description: 根据机构名称获取机构信息
	 * @date 2016年12月8日 下午9:55:20
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public List<Organization> getOrganizationByName(String name) {
		return Db.querySqlList(Organization.class, OrganizationSQL.ORGANIZATION_BY_NAME, name);
	}

	/**
	 * @Description: 根据id获取机构（机构添加）
	 * @date 2016年12月9日 下午2:48:51
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public Organization getOrganizationInfo(Integer organizationId) {
		return Db.findById(organizationId, Organization.class);
	}

	/**
	 * @Description:根据机构id获取城市机构关联信息
	 * @date 2016年12月9日 下午3:09:40
	 * @author SUNZHICHENG
	 * @since V2.6.2
	 */
	@Override
	public CityRefOrganization getCityRefOrganization(Integer organizationId) {
		return Db.querySqlFirst(CityRefOrganization.class, OrganizationSQL.QUERY_ORGANIZATION_CITY, organizationId);
	}

}
